﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.Admin;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Customer_Profile.eCard.Settle
{
    public partial class SettleCheck_List : System.Web.UI.Page
    {
        string strUserName = "";
        string strUserID = "";
        string strEntity = "";

        
        string sumDueAmount = "";
        string sumSettleAmount = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }
            string strURL = HttpContext.Current.Request.Url.AbsolutePath;
            bool bok = Comm.ifhasright(strUserID, strURL);
            if (!bok)
            {
                Response.Write("你无权访问此页面");
                Response.End();
            }

            if (!Page.IsPostBack)
            {
                //Comm.BindDll(ref dropTerm, "TermType", true, "");
                DataSet dsProd = ProductDao.getAllProduct("ALL");
                dropProd.DataSource = dsProd;
                dropProd.DataTextField = "procduct_name";
                dropProd.DataValueField = "procduct_code";
                dropProd.DataBind();
                ListItem liAll = new ListItem();
                liAll.Text = "All";
                liAll.Value = "All";
                dropProd.Items.Insert(0, liAll);

                //Comm.BindDll(ref dropEntity, "Entity", true, "");
                //DataSet dsEntity = EntityDao.getEntityList("N");
                //dropEntity.DataSource = dsEntity;
                //dropEntity.DataTextField = "entity_name";
                //dropEntity.DataValueField = "entity_name";
                //dropEntity.DataBind();
                //ListItem liAllEntity = new ListItem();
                //liAllEntity.Text = "All";
                //liAllEntity.Value = "All";
                //dropEntity.Items.Insert(0, liAllEntity);
                //dropEntity.Items.FindByValue(strEntity).Selected = true;
                //dropEntity.Enabled = false;

                //txtcreatedatebegin.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                //txtcreatedateend.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            bindGrid();
        }

        private void bindGrid()
        {
            try
            {                
                string strWhere = " where ss.settle_status ='SV' ";

                if (txtCardNo.Text.Trim() != "")
                    strWhere += " and d.card_no ='" + txtCardNo.Text.Trim() + "'";
                if (txtCpartyName.Text.Trim() != "")
                    strWhere += " and c.cparty_name like '%" + txtCpartyName.Text.Trim() + "%'";
                if (dropProd.SelectedIndex > 0)
                {
                    strWhere += " and d.prod_code = '" + dropProd.SelectedItem.Value + "'";
                }
                if (txtcreatedatebegin.Text != "" && txtcreatedateend.Text != "")
                    strWhere += " and convert(date,d.due_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";

                strWhere += " ORDER BY deal_no DESC";

                DataSet ds = DealDao.getCardSettleDeals(strWhere);
                if (ds != null && ds.Tables.Count > 0)
                {
                    sumDueAmount = ds.Tables[0].Compute("sum(due_amount)", "1>0").ToString();
                    sumSettleAmount = ds.Tables[0].Compute("sum(settle_amount)", "1>0").ToString();
                    GvData.DataSource = ds;
                    GvData.DataBind();
                }
                else
                {
                    GvData.DataBind();
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindGrid", ex.ToString());
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

        }

        protected void GvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GvData.PageIndex = e.NewPageIndex;
            bindGrid();
        }

        protected void GvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lb = (LinkButton)e.Row.Cells[1].Controls[1];
                lb.Attributes.Add("onclick", "javascript:window.open('/eCard/CardDetail.aspx?cardno=" + lb.Text + "');return false");
                string settle_id = GvData.DataKeys[e.Row.RowIndex].Values["settle_id"].ToString(); //e.Row.Cells[4].Text;                
                LinkButton lbAction = (LinkButton)e.Row.Cells[11].Controls[1];                                
                lbAction.Attributes.Add("onclick", "javascript: var s_height = screen.height - 75; window.open('Settle_check.aspx?settle_id=" + settle_id + "', 'newwindow1', 'width=' + screen.width + ',height=' +  s_height + ',top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');return false");
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "合计";
                e.Row.Cells[0].ForeColor = System.Drawing.Color.White;
                e.Row.Cells[7].Text = sumDueAmount;
                e.Row.Cells[7].ForeColor = System.Drawing.Color.White;
                e.Row.Cells[8].Text = sumSettleAmount;
                e.Row.Cells[8].ForeColor = System.Drawing.Color.White;                
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //标题
            byte[] bTitle = System.Text.Encoding.GetEncoding("UTF-8").GetBytes("交易信息" + "<br><br>");
            StringBuilder sb = new StringBuilder();
            sb.Append(System.Text.Encoding.GetEncoding("UTF-8").GetString(bTitle));

            //报表内容
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            GvData.AllowPaging = false;
            GvData.ShowHeader = true;
            bindGrid();
            GvData.RenderControl(oHtmlTextWriter);
            byte[] bContent = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(oStringWriter.ToString());
            sb.Append(System.Text.Encoding.GetEncoding("UTF-8").GetString(bContent));

            //输出
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "UTF-8";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=settle-mmdeals.xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            System.Web.HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";    //设置输出文件类型为excel文件。 
            System.Web.HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=" + "UTF-8" + "\" >");

            string strExcel = sb.ToString();

            //去除超链接 
            strExcel = Regex.Replace(strExcel, "<a (.*?)>", "", RegexOptions.Compiled);
            strExcel = Regex.Replace(strExcel, "</a>", "");

            System.Web.HttpContext.Current.Response.Write(strExcel);
            System.Web.HttpContext.Current.Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
}